/**
 * Created by ziyu on 2017/7/28.
 */
/**
 * Created by ziyu on 17/3/7.
 */
import React, {Component, PropTypes} from 'react'
import moment from 'moment'
import Styles from './Index.less'
import SearchStyle from '../../common/less/search.less'
import {message, Col, Icon} from 'antd'
import {fetchPost} from '../../../utils/request'
import List from './OrderViewList'
import Search from '../../common/components/Search'
import Detail from './detail/Detail'
import $ from 'jquery'

class Index extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isNewAdd: props.isNewAdd,
      processNode: props.processNode,
      signStatus: props.signStatus,
      userId: null,
      orderStatus: null,
      getListApi: props.getListApi,
      id: null,
      refresh: false,
      processingCount: null,
      stepType: props.stepType,
      list: [],
      item: {},
      isFetch: false,
      showList: 'show',
      page: {
        currentPage: 1,
        pageSize: 13,
        totalCount: 0,
      },
      params: {
        findtype: '',
        duration: '',
        realCapital: '',
        inputValue: '',
        startDate: moment().subtract('days', 30).format('YYYY-MM-DD'),
        endDate: moment().add('days', 30).format('YYYY-MM-DD'),
      },
      activeKey: 'detail',
      searchParams: props.stepType == 'unAssignedOrder' ?
        {
          list: [
            {
              name: 'Date',
              type: 'range',
              key: ['startDate', 'endDate'],
              className: 'pr20',
              placeHolder: '',
              values: [
                moment().subtract('days', 30),
                moment().add('days', 30)
              ]
            },
            {
              name: '',
              type: 'buttonRadio',
              key: 'isNewAdd',
              className: 'pr20',
              values: [
                {
                  value: '',
                  name: 'All',
                },
                {
                  value: '0',
                  name: 'New Application',
                },
                {
                  value: '1',
                  name: 'Repeat Application',
                }],
            },
            {
              name: '',
              type: 'buttonRadio',
              key: 'trafficType',
              className: 'pr20',
              values: [
                {
                  value: '',
                  name: 'All'
                },
                {
                  value: 'promotion',
                  name: 'Promotion'
                },
                {
                  value: 'nature',
                  name: 'Organic'
                }
              ],
            },
            {
              name: 'Filter',
              type: 'group',
              key: ['findtype', 'inputValue'],
              className: 'pr20',
              values: [{value: '', name: 'Please Choose'}],
            },
            {
              name: 'Channel',
              type: 'newSelect',
              key: 'channelCode',
              className: 'pr20',
              values: []
            },
            {
              name: '',
              type: 'search',
              key: '',
              className: 'pr20',
              values: [],
            }

          ],
          api: '/common/query',
        }
        :
        {
          list: [
            {
              name: props.stepType == 'passOrder' ? 'Approved Date' : "Rejected Date",
              type: 'range',
              key: ['startDate', 'endDate'],
              className: 'pr20',
              placeHolder: '',
              values: [
                moment().subtract('days', 30),
                moment().add('days', 30)
              ]
            },
            {
              name: '',
              type: 'buttonRadio',
              key: 'isNewAdd',
              className: 'pr20',
              values: [
                {
                  value: '',
                  name: 'All',
                },
                {
                  value: '0',
                  name: 'New Application',
                },
                {
                  value: '1',
                  name: 'Repeat Application',
                }],
            },
            {
              name: '',
              type: 'buttonRadio',
              key: 'trafficType',
              className: 'pr20',
              values: [
                {
                  value: '',
                  name: 'All'
                },
                {
                  value: 'promotion',
                  name: 'Promotion'
                },
                {
                  value: 'nature',
                  name: 'Organic'
                }
              ],
            },
            {
              name: 'Filter',
              type: 'group',
              key: ['findtype', 'inputValue'],
              className: 'pr20',
              values: [{value: '', name: 'Please Choose'}],
            },
            {
              name: 'E-sign status',
              type: 'select',
              key: 'signStatus',
              className: 'pr300',
              values: [
                {
                  value: '1',
                  name: 'Success'
                },
                {
                  value: '2',
                  name: 'Failed'
                },
                {
                  value: '9',
                  name: 'Waiting e-sign'
                }
              ]
            },
            {
              name: 'Channel',
              type: 'newSelect',
              key: 'channelCode',
              className: 'pr20',
              values: []
            },
            {
              name: '',
              type: 'search',
              key: '',
              className: 'pr20',
              values: [],
            }

          ],
          api: '/common/query',
        },
      detailDom: '',
    }
  }

  componentDidMount() {
    this.state.detailDom = $('#detailClass')
    this.getData()
    // this.state.detailDom.addClass('animated fadeInRightBig').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
    //   $(this).removeClass('animated fadeInRightBig');
    // });
  }

  currentPage(current) {
    this.setState({
      page: {
        ...this.state.page,
        currentPage: current,
      },
    }, () => {
      this.getData()
    })
  }

  getData() {
    let copyState = {}
    let self = this
    for (let i in this.state.params) {
      if (this.state.params[i] != '') {
        copyState[i] = this.state.params[i]
      }
    }
    if (!copyState.startDate) {
      copyState.startDate = moment().subtract('days', 30).format('YYYY-MM-DD')
    }
    if (!copyState.endDate) {
      copyState.endDate = moment().add('days', 30).format('YYYY-MM-DD')
    }

    fetchPost(
      `${this.state.getListApi}?currentPage=${this.state.page.currentPage}&pageSize=${this.state.page.pageSize}`,
      {
        signStatus: this.state.signStatus,
        processNode: this.state.processNode,
        ...copyState
      }).then((res) => {
      if (res.code === 0) {
        let list = res.data.list
        if (list.length > 0 && list != null) {
          this.setState({
            id: list[0].auditNo,
            userId: list[0].tradeNo,
            page: {
              ...this.state.page,
              totalCount: res.page.totalCount || 0,
            },
            orderStatus: list[0].orderStatus,
            item: list[0],
            activeKey: 'detail',
            isFetch: true,
            list,
          })
        } else {
          self.setState({
            id: null,
            userId: null,
            orderStatus: null,
            item: {},
            activeKey: 'detail',
            isFetch: true,
            list: [],
            page: {
              ...this.state.page,
              totalCount: res.page.totalCount || 0,
            },
          })
          message.warning("There's No data")
        }
      } else {
        self.setState({
          id: null,
          userId: null,
          orderStatus: null,
          item: {},
          activeKey: 'detail',
          isFetch: true,
          list: [],
        }, () => {
          message.error(res.msg)
        })
      }
    })
  }

  changeParams(params) {
    if (params.inputValue) {
      if (params.findtype) {
        this.setState({
          params,
          isFetch: false,
        }, () => {
          this.getData()
        })
      } else {
        message.warning('Please choose the filter')
      }
    } else {
      this.setState({
        params,
        isFetch: false,
      }, () => {
        this.getData()
      })
    }
  }

  chooseOrder(params) {
    console.log(params);
    this.setState({
      id: params.id,
      userId: params.userId,
      orderStatus: params.orderStatus,
      activeKey: params.activeKey,
      item: params.item,
      isFetch: false,
    })
  }

  changeOrder(type, id) {
    setTimeout(() => {
      this.state.list.forEach((val, index) => {
        if (val.auditNo == id) {
          this.state.list.splice(index, 1)
        }
      })

      let list = this.state.list
      if (list.length === 0) {
        this.getData()
      } else {
        this.setState({
          id: list[0].auditNo,
          userId: list[0].tradeNo,
          orderStatus: list[0].orderStatus,
          item: list[0],
          activeKey: 'detail',
          list,
          isFetch: false,
        })

        // this.state.detailDom.addClass('animated fadeInRightBig').
        //   one(
        //     'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend',
        //     function () {
        //       $(this).removeClass('animated fadeInRightBig')
        //     })
      }
    }, 500)
  }

  showList() {
    return `${Styles.listClass}
    // ${Styles.listRight}`
  }

  detailClass() {
    return `${Styles.detailClass} 
    // ${Styles.detailRight}`
  }

  render() {
    console.log(this.state.page, 'page')
    return (
      <div className={Styles.box}>
        <div className={SearchStyle.searchClass}>
          <Search searchParams={this.state.searchParams}
                  changeParams={(params) => this.changeParams(params)}/>
        </div>

        <div className={Styles.detailWrapper}>
          <div
            className={this.showList()}
          >
            <div>
              <List
                list={this.state.list}
                id={this.state.id}
                userId={this.state.userId}
                isFetch={this.state.isFetch}
                stepType={this.state.stepType}
                page={this.state.page}
                chooseOrder={(params) => this.chooseOrder(params)}
                currentPage={(current) => this.currentPage(current)}
              />
            </div>
          </div>

          <div id='detailClass' className={this.detailClass()}
          >
            <Detail
              activeKey={this.state.activeKey}
              id={this.state.id}
              userId={this.state.userId}
              tradeNo={this.state.userId}
              stepType={this.state.stepType}
              orderStatus={this.state.orderStatus}
              item={this.state.item}
              processNode={this.state.processNode}
              changeOrder={(type, id) => this.changeOrder(type, id)}/>
          </div>
        </div>

      </div>
    )
  }
}

export default Index
